package com.deloitte.snap.util;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;



public class FileUploadController extends HttpServlet   
{	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static String rootPath;
	private static String fileSeparator;
	private static String downloadInfo;
	private static Properties prop=new Properties();
	static
	{
		try
		{
			InputStream is=FileUploadController.class.getClassLoader().getResourceAsStream("file.properties");			
			prop.load(is);
			is.close();		
			rootPath = prop.getProperty("rootpath");
			fileSeparator = prop.getProperty("fileseparator");
			downloadInfo =  prop.getProperty("downloadInfo");
		}
		catch(Exception exc)
		{
			exc.printStackTrace();
		}
	}
	public void doGet(HttpServletRequest req,HttpServletResponse res)  
	{
		doPost(req, res);
	}
	public void doPost(HttpServletRequest req,HttpServletResponse res)  
	{
		
		try 
		{			
			String doctype = req.getParameter(prop.getProperty("doctype"));
			String projectphase = req.getParameter(prop.getProperty("projectphase"));
			String delmastercode = req.getParameter(prop.getProperty("delmastercode"));
			
			String fileName = req.getParameter(prop.getProperty("filename"));
			StringBuffer relativepath = new StringBuffer();
			
			if(!CommonUtil.isEmpty(doctype)){
				relativepath.append(fileSeparator).append(doctype);
			}
			if(!CommonUtil.isEmpty(projectphase)){
				relativepath.append(fileSeparator).append(projectphase);
			}
			/*
			 * Create file name
			 */
			
			if(!CommonUtil.isEmpty(fileName)){
				StringBuffer genFileName = new StringBuffer();
				if(!CommonUtil.isEmpty(delmastercode)){
					genFileName.append(delmastercode).append("_");
				}
				genFileName.append(fileName);
				int indexOfFileExtn = genFileName.lastIndexOf(".");
				genFileName.insert(indexOfFileExtn,"_"+CommonUtil.getCurrentTime());
				fileName = genFileName.toString();
			}
			
			String path = rootPath+relativepath.toString();
			System.out.println("path "+path);
			if(path!=null && path.trim().length()>0)
			{
				boolean success = (new File(path)).mkdirs();
			    System.out.println(" directory created : "+success);
			}
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(-1);
			List fileItems = upload.parseRequest(req);
			Iterator itr = fileItems.iterator();
			while(itr.hasNext())
			{
				FileItem fileItem = (FileItem) itr.next();
				if(!fileItem.isFormField())
				{	
					if(fileName == null || fileName.trim().length() == 0)
						fileName = fileItem.getName();
				
					File file = new File(path,fileName);	
					System.out.println(" fileName created : "+fileName);
					fileItem.write(file);
				}
			}
			/*
			 * Write docdetailid and file location to the response
			 */
			
			res.getWriter().write((relativepath.append(fileSeparator).append(fileName)).toString());
			res.getWriter().flush();
			res.getWriter().close();
			
		} catch (Exception e) 
		{
			e.printStackTrace();			
		}
		
	}
	
	
	
	public static boolean deleteFile(String relFilePath)
	{
		try
		{
			System.out.println("relFilePath "+relFilePath);
			if(relFilePath != null && relFilePath.trim().length()>0)
			{
				String filePath = rootPath+relFilePath;
				System.out.println("filePath "+filePath);
				File file = new File(filePath);
				
				if(file.exists())
				{
					return file.delete();
				}
			}
		}
		catch(Exception exc)
		{
			
		}
		return false;
	}
	
	
	public static String getRootPath() 
	{
		return rootPath;
	}
	
	public static String getFileSeparator() 
	{
		return fileSeparator;
	}
	
	public static String getDownloadInfo() 
	{
		return downloadInfo;
	}

}
